<?php

namespace backend\models;

use Yii;
use common\models\UserInfo;
use backend\models\UserCoupon;
use backend\models\GrpCity;
use backend\models\OperatorRelation;
/**
 * This is the model class for table "pay_trade".
 *
 * @property integer $id
 * @property string $trade_no
 * @property integer $user_id
 * @property string $address
 * @property string $message
 * @property integer $number
 * @property string $price
 * @property string $price_modify
 * @property string $price_m_memo
 * @property string $price_freight
 * @property string $price_total
 * @property integer $price_state
 * @property integer $create_time
 * @property integer $modify_time
 * @property integer $admin_uid
 * @property integer $trade_state
 * @property integer $audit_state
 * @property integer $audit_uid
 * @property integer $audit_time
 * @property string $content
 */
class PayTrade extends \yii\db\ActiveRecord
{
	public $username;
	public $admin_username;
	public $audit_username;
	public $create_datetime;
	public $modify_datetime;
	public $audit_datetime;
	public $modify_admin_username;
	public $start_time;
	public $end_time;
	public $amount;
	public $pay_amount;
	public $operator_id;
	public $operator_address;
	public $audit_offline_pay;
	public $originPrice;
	
	public $quarter_one;//第一季度订单金额
	public $quarter_two;//第二季度订单金额
	public $quarter_three;//第三季度订单金额
	public $quarter_four;//第四季度订单金额
	public $year;//年份
	public $nickname;
	public $user_area;
	public $tel;
	public $user_type_class;
	public $prepay_id;
	public $desc;
	 
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'pay_trade';
        
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['user_id', 'number', 'price_state',   'admin_uid', 'modify_uid',	'trade_state', 'audit_state', 'refund_audit'], 'integer'],
            [['address', 'message', 'price_m_memo'], 'string'],
            [['price', 'price_modify', 'price_freight', 'price_total','refund_bfb','refund_price','audit_offline_pay','audit_offline_pay','originPrice'], 'number'],
            [['trade_no'], 'string', 'max' => 64],
            [['trade_no'], 'unique'],
            [['content','create_time','refund_time'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'trade_no' =>Yii::t('app','Trade No'),
            'user_id' => Yii::t('app','User ID'),
            'address' => Yii::t('app','Trade Address'),
            'message' => Yii::t('app','Trade Message'),
            'number' => Yii::t('app','Trade Number'),
            'price' => Yii::t('app','Trade Price'),
            'price_modify' => Yii::t('app','Trade Price Modify'),
            'price_m_memo' => Yii::t('app','Trade Price M Memo'),
            'price_freight' => Yii::t('app','Trade Price Freight'),
            'price_total' => Yii::t('app','Trade Price Total'),
            'price_state' => Yii::t('app','Trade Price State'),
            'create_time' => Yii::t('app','Trade Create Time'),
            'modify_time' => Yii::t('app','Trade Modify Time'),
            'admin_uid' => Yii::t('app','Trade Admin Uid'),
            'trade_state' => Yii::t('app','Trade Trade State'),
            'audit_state' => Yii::t('app','Trade Audit State'),
            'audit_uid' => Yii::t('app','Trade Audit Uid'),
            'audit_time' => Yii::t('app','Trade Audit Time'),
            'content' => Yii::t('app','Trade Content'),
            'username' => Yii::t('app','Trade Username'),
            'admin_username'=>Yii::t('app','Trade Admin Username'),
            'audit_username'=>Yii::t('app','Trade Audit Username'),
            'create_datetime' => Yii::t('app','Trade Create Time'),
            'modify_datetime' => Yii::t('app','Trade Modify Time'),
            'audit_datetime' => Yii::t('app','Trade Audit Time'),
            'modify_uid' =>  Yii::t('app','Modify Admin'),
            'modify_admin_username' =>  Yii::t('app','Modify Admin'),
            'refund_bfb' =>  Yii::t('app','Refund Bfb'),
            'refund_price' =>  Yii::t('app','Refund Price'),
            'refund_time' =>  Yii::t('app','Refund Time'),
            'refund_audit' =>  Yii::t('app','Refund Audit'),
            'audit_offline_pay' => Yii::t('app', 'Audit Offline Pay'),
        	'year'=>Yii::t('app', '年份'),	
            'originPrice'=>Yii::t('app', 'Trade Price Total'),
        		'nickname' =>  Yii::t('app','用户名'),
        		'user_area' =>  Yii::t('app','所属地区'),
        		'tel' => Yii::t('app', '电话'),
        		'user_type_class'=>Yii::t('app', '用户级别'),
        		'quarter_one'=>Yii::t('app', '第一季度'),
        		'quarter_two'=>Yii::t('app', '第二季度'),
        		'quarter_three'=>Yii::t('app', '第三季度'),
        		'quarter_four'=>Yii::t('app', '第四季度'),
        		
        		
        ];    
    }
    public function getPayLogistics()
    {
        return $this->hasMany(PayLogistics::className(), ['trade_id'=>'id']);
    }
   
    
    public function getCrowdPrice(){
        return $this->hasOne(CrowdItemPrice::className(), ['id'=>'crowd_price_id']);
    }
    //外连用户信息
    public function getUserInfo()
    {
    	return $this->hasOne(UserInfo::className(),['id'=>'user_id']);
    }
    //外链跟单客服信息
    public function getAuditInfo()
    {
    	return $this->hasOne(AdminInfo::className(),['id'=>'audit_uid']);
    }
    //外链审核员信息
    public function getAdminInfo()
    {
    	return $this->hasOne(AdminInfo::className(),['id'=>'admin_uid']);
    }
    
    
    //外链改价员信息
    public function getModifyAdminInfo()
    {
    	return $this->hasOne(AdminInfo::className(),['id'=>'modify_uid']);
    }
    
    //外链支付信息
    public function getLogPayInfo()
    {
    	return $this->hasOne(LogPay::className(),['trade_no'=>'trade_no']);
    }
    //外连支付信息1:n
    public function getLogPayInfoMore()
    {
    	return $this->hasMany(LogPay::className(),['trade_no'=>'trade_no']);
    }
    public function getLogPayInfoFirst()
    {
        return $this->hasOne(LogPay::className(),['trade_no'=>'trade_no'])->onCondition('trade_no_count = 1');
    }
    //已支付金额和
    public function getPayedAmount(){
        $amountInfo = self::findBySql("select sum(rmb) as amount from log_pay where trade_no='{$this->trade_no}' AND state in (1,2)")->one();
        return floatval($amountInfo['amount']);
    }
    //订单所属省市
    public static function belongArea($address){
    	if($address){
    		$arr = explode(" ", $address);
    		if(in_array($arr[0], Yii::$app->params['ZXS']))	//直辖市
    			$area = $arr[0];
    		else
    			$area = implode(" ", array($arr[0],$arr[1]));
    		return $area;
    	}
    }
    //订单所属运营商
    public static function belongOperator($address){
    	if($address){
    		$area = self::belongArea($address);
    		return SysUserDesigner::infoByAddressAndType($area);
    	}
    }
    //订单所属运营商
    public static function belongOperator_new($address){
        $addressArray=explode(" ",$address);
        $province=$addressArray[0];
        $city=$addressArray[1];
        $operatorId=0;
        if(in_array($province, Yii::$app->params['ZXS'])){
            $country=$addressArray[1];
            $city=$addressArray[0];
        }else{
            $country=$addressArray[2];
        }
        //先根据区县  查询运营商 如果不存在，则查询城市
        $sql="select id from grp_city where name=:name";
        $param=array(":name"=>$country);
        $countryId=GrpCity::findBySql($sql,$param)->asArray()->one();
        $countryId=$countryId['id'];
        
        $sql="select uid from prf_operator_relation where city_list like '%{$countryId}%'  and useing=1";
        $Operator=OperatorRelation::findBySql($sql)->asArray()->one();
        if(count($Operator)>0){
            $operatorId=$Operator['uid'];
        }else{
            $sql="select id from grp_city where name=:name";
            $param=array(":name"=>$city);
            $city=GrpCity::findBySql($sql,$param)->asArray()->one();
            $city=$city['id'];
            $sql="select uid from prf_operator_relation where city_list like '%{$city}%'   and useing=1";
            $Operator=OperatorRelation::findBySql($sql)->asArray()->one();
            if(count($Operator>0)){
                $operatorId=$Operator['uid'];
            }
        }
        
        $company="";
        if(intval($operatorId)>0){
            $sql="SELECT company FROM sys_user_designer WHERE uid=:uid";
            $param=array(":uid"=>$operatorId);
            $designer=SysUserDesigner::findBySql($sql,$param)->asArray()->one();
            if(count($designer)>0){
                $company=$designer['company'];
            }
        }
        return $company;
    }
    //重新计算一遍订单，$order=json_decode($this->content)
    public function calcContent($order)
    {
        $total_price=0;
        $total_count=0;
        foreach ($order as $type => $set)
        {
            foreach ($set as $n => $m)
            {
                $info=$m['info'];
                foreach ($m['items'] as $i => $item)
                {
                    //如果是赠品，则跳过计算
                    if (isset($info['exclude'])&&!empty($info['exclude'])&&in_array($item['item_id'], $info['exclude']))
                    {
                        continue;
                    }
                    //如果存在用户折扣
                    if (isset($info['user_discount'])){
                        //price_base是否为0，是的话final_price为0，否则final_price = ( 基础价 + 定制价 ) * 用户折扣
                        intval($item["price_base"])>0?$order[$type][$n]['items'][$i]['final_price']=intval(($item["price_base"]+$item["_price_custom"])*$info['user_discount']):$order[$type][$n]['items'][$i]['final_price']=0;
                    }
                    //如果不存在用户折扣，存在套装折扣
                    elseif (isset($info['discount'])){
                        //判断套装折扣是否为0，是的话折扣自动变1
                        $discount=floatval($info['discount'])==0?1:floatval($info['discount']);
                        //price_base是否为0，是的话final_price为0，否则final_price = ( 基础价 * 折扣  + 定制价  * 定制折扣 ) * 套装折扣
                        intval($item["price_base"])>0?$order[$type][$n]['items'][$i]['final_price']=intval(($item["price_base"]*$item['price_discount']+$item["_price_custom"]*$item["_price_discount"])*$info['discount']):$order[$type][$n]['items'][$i]['final_price']=0;
                    }
                    //否则计算单品本身折扣：final_price = ( 基础价 * 折扣  + 定制价  * 定制折扣 )
                    else {
                        intval($item["price_base"])>0?$order[$type][$n]['items'][$i]['final_price']=intval($item["price_base"]*$item['price_discount']+$item["_price_custom"]*$item["_price_discount"]):$order[$type][$n]['items'][$i]['final_price']=0;
                    }
                
                    //计算final_price，未乘info里的count
                    $t=$order[$type][$n]['items'][$i]['final_price']*$item['count'];
                
                    //如果info里有count，则再乘上此count
                    if (isset($info['count'])&&$info['count']>1) {
                        $total_price=$total_price+$t*intval($info['count']);
                        $total_count=$total_count+$item['count']*intval($info['count']);
                    }else{
                        $total_price=$total_price+$t;
                        $total_count=$total_count+$item['count'];
                    }
                }
            }
        }
        $this->price=$total_price;
        $this->price_modify=$total_price;
        $this->number=$total_count;
        $this->content=json_encode($order,JSON_UNESCAPED_UNICODE);
        return true;
    }
    
    //改变订单条件（用户）
    public function changeUser()
    {
        $cart_type=[
            //user_shopping里的type => pay_user_discount里的sales_type
            '0'=>1,
            '1'=>2,
            '2'=>3,
            '3'=>4,
            'singleItem'=>1,
            'tz'=>2,
            'GJJPackage'=>3
        ];
        if($this->user_id)
        {
            $user_discount=PayUserDiscount::getUserDiscountByUserid($this->user_id);
            $order=json_decode($this->content,true);
            //订单重新设置需要更改的值
            foreach ($order as $type => $set)
            {
                foreach ($set as $n => $m)
                {
                    $info=$m['info'];
                    if (isset($order[$type][$n]['info']['user_discount'])&&isset($user_discount[$cart_type[$type]]['discount']))
                    {
                        $order[$type][$n]['info']['user_discount']=$user_discount[$cart_type[$type]]['discount'];
                    }
                    else
                    {
                        echo '用户不是VIP会员，不存在用户折扣';
                        return false;
                    }
                }
            }
            if (self::calcContent($order)){
                return true;
            }else{
                return false;
            }
        }
    }

    static function calculate($json){
    	 $originPrice = 0.00;
         if(!empty($json)){
         	$obj = json_decode($json);
         	//单品
         	if(isset($obj->singleItem) && !empty($obj->singleItem)){
         		foreach ($obj->singleItem as $v){
	         		if(isset($v->items) && !empty($v->items)){        			
	         			foreach ($v->items as $val){
	         				$originPrice += ($val->price_base + $val->_price_custom) * $val->count;
	         			}
	         		}
         		}     		 
         	}
         	//套餐
         	if(isset($obj->tz) && !empty($obj->tz)){
         		foreach ($obj->tz as $v){
         			if(isset($v->items) && !empty($v->items)){
         				foreach ($v->items as $val){
         					$originPrice += ($val->price_base + $val->_price_custom) * $val->count;
         				}
         			}
         		}
         	}
         }
    	 
		return ['originPrice'=>sprintf('%.2f',$originPrice)];
    }
    /**
     * 显示优惠券
     * @param array $coupon
     */
   	public static function  showCoupon($coupon,$type){
   		if(!in_array($type,Yii::$app->params['COUPON_TYPE']))
   			return ;
    	$name = isset($coupon['name'])?(string)$coupon['name']:'';
    	$title = isset($coupon['title'])?(string)$coupon['title']:'';
    	$start_time = isset($coupon['start_time'])&&!empty($coupon['start_time'])?date('Y-m-d H:i:s',$coupon['start_time']):'';
    	$end_time = isset($coupon['end_time'])&&!empty($coupon['end_time'])?date('Y-m-d H:i:s',$coupon['end_time']):'';
    	$coupon_rule = isset($coupon['coupon_rule'])  && isset(Yii::$app->params['COUPON_RULE'][$coupon['coupon_rule']])?(string)Yii::$app->params['COUPON_RULE'][$coupon['coupon_rule']]:'';
    	$coupon_price = isset($coupon['coupon_price'])?(string)$coupon['coupon_price']:'';
    	$price = isset($coupon['price'])?(string)$coupon['price']:'';
    	$memo = isset($coupon['memo'])?(string)$coupon['memo']:'';
    	$url = isset($coupon['url'])?(string)$coupon['url']:'';
    		
    	echo '<tr style="color:blue;font-weight:bold;"><td colspan="9">'.Yii::$app->params['COUPON_TYPE_NAME'][$type].'优惠券</td></tr>';
    	echo '<tr>';
    	echo '<td>'.$name.'</td>';
    	echo '<td>'.$title.'</td>';
    	echo '<td>'.$start_time.'</td>';
    	echo '<td>'.$end_time.'</td>';
    	echo '<td>'.$coupon_rule.'</td>';
    	echo '<td>'.$coupon_price.'</td>';
    	echo '<td>'.$price.'</td>';
    	echo '<td>'.$memo.'</td>';
    	echo '<td style="">'."<span><img src='$url' alt='图片' /></span>".'</td>';
    	echo '</tr>';
    
    }
    /**
     * object转数组 递归
     * @param unknown $data
     */
	public function obj2array($data){
		$newArray=array();
		foreach($data as $key=>$value){
			if(is_object($value)){
				$newArray[$key]=$this->obj2array($value);
			}else{
			$newArray[$key]=$value;
			}
		}
		return $newArray;
	}
	/**
	 * 根据设计师id或者装饰公司id 获取使用了优惠券的订单总金额
	 */
   public function getUserCouponByDes($year,$userid,$quarty){
   		$unixTime=$this->getUnixTimeByQuarty($year,$quarty);
	   	$sql="SELECT  SUM(pay_trade. price_modify ) price_modify  FROM  pay_trade
				LEFT JOIN user_coupon ON   SUBSTRING(LEFT(SUBSTRING(content, LOCATE('\"coupon\":{\"all\":{\"id\":\"', content)), (LOCATE('\",', SUBSTRING(content, LOCATE('\"coupon\":{\"all\":{\"id\":\"', content))))
				),24,LENGTH(LEFT(SUBSTRING(content, LOCATE('\"coupon\":{\"all\":{\"id\":\"', content)), (LOCATE('\",', SUBSTRING(content, LOCATE('\"coupon\":{\"all\":{\"id\":\"', content))))
				))-24)=user_coupon.id
				WHERE  trade_class=1 and  price_state IN (1,11)  AND content  LIKE '%\"coupon\":{\"all\"%'
				AND from_uid=:fromuid  and pay_trade.create_time>=:begin_time and pay_trade.create_time<=:end_time;";
	   	$param=array(":fromuid"=>$userid,":begin_time"=>$unixTime['begin_time'],":end_time"=>$unixTime['end_time']);
	   	$price=PayTrade::findBySql($sql,$param)->asArray()->one();
	   	return $price['price_modify'];
   }
    /**
    * 获取设计师  装饰公司的每季度消费总金额  
    */
   public function getPriceByUserid($year,$userid,$quarty){
   		$unixTime=$this->getUnixTimeByQuarty($year,$quarty);
		$sql="select  sum(price_modify) price_modify  from pay_trade
				where  trade_class=1 and price_state in (1,11) and user_id=:user_id and create_time>=:begin_this_quarter and create_time<=:end_this_quarter";
		$param=array(":user_id"=>$userid,":begin_this_quarter"=>$unixTime['begin_time'],":end_this_quarter"=>$unixTime['end_time']);
		$price=PayTrade::findBySql($sql,$param)->asArray()->one();
		return $price['price_modify'];
   }
   /**
    * 根据userid和季度 获取设计师以及使用当前设计师的优惠券的用户的总金额统计
    * 计算全年  $quarty=0
    * 
    */
   public function getSumPriceByUserid($year,$userid,$quarty){
   	$priceOne=doubleval($this->getPriceByUserid($year,$userid, $quarty));
  	$priceTwo=doubleval($this->getUserCouponByDes($year,$userid, $quarty));
   	$acountPrice=$priceOne+$priceTwo;
   	return $acountPrice;
   }
 
   /**
    * 根据季度获取时间挫
    */
   public function getUnixTimeByQuarty($year,$quarty){
   	 $unixTime=array();
   	 if($year==''){
   	 	$year=date("y");
   	 }
   	 switch($quarty){
   	 	//一季度是1月1日到3月31日；二季度是4月1日到6月30；三季度是7月1到9月30；四季度是10月1到12月31
   	 	case 1:
   	 		$begin_this_quarter=strtotime(date("$year-01-01 00:00:00"));
   	 		$end_this_quarter=strtotime(date("$year-03-31 23:59:59"));
   	 		//第一节度范围内
   	 		break;
   	 	case 2:
   	 		$begin_this_quarter=strtotime(date("$year-04-01 00:00:00"));
   	 		$end_this_quarter=strtotime(date("$year-06-30 23:59:59"));
   	 		break;
   	 	case 3:
   	 		$begin_this_quarter=strtotime(date("$year-07-01 00:00:00"));
   	 		$end_this_quarter=strtotime(date("$year-09-30 23:59:59"));
   	 		break;
   	 	case 4:
   	 		$begin_this_quarter=strtotime(date("$year-10-01 00:00:00"));
   	 		$end_this_quarter=strtotime(date("$year-12-31 23:59:59"));
   	 		break;
   	 	default:
   	 		$begin_this_quarter=strtotime(date("$year-01-01 00:00:00"));
   	 		$end_this_quarter=strtotime(date("$year-12-31 23:59:59"));
   	 		break;
   	 }
   	 $unixTime['begin_time']=$begin_this_quarter;
   	 $unixTime['end_time']=$end_this_quarter;
   	 return $unixTime;
   }
   
}
